import logging
import os
import json

from dotenv import load_dotenv
from playwright.sync_api import BrowserContext, expect, Page


def check_storage_file_exists(file_path):
    if not os.path.exists(file_path):
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump({}, f, ensure_ascii=False, indent=4)


def is_logged_in(page: Page) -> bool:
    """
    检查是否已登录（已登录的的话会重定向到控制面的主页）
    :param page: Playwright page 对象
    :return: 是否已登录
    """
    page.goto('/oauth2/auth/login/fuyaoPasswordProvider')
    page.wait_for_load_state('networkidle')
    current_url = page.url
    return '/oauth2/auth/login/fuyaoPasswordProvider' not in current_url


def login(context: BrowserContext, credentials: dict[str, str]) -> None:
    """
    执行登录操作。
    """    
    logger = logging.getLogger(__name__)
    page = context.new_page()

    if is_logged_in(page):
        logger.info('Already logged in.')
    else:
        logger.info('Not logged in, attempting login...')
        page.get_by_label('用户名').fill(credentials['username'])
        page.get_by_label('密码').fill(credentials['password'])
        page.get_by_role('button', name='登录').click()

        expect(page.get_by_text("集群：")).to_be_visible()
        logger.info('Login successful.')

    page.close()
